function [keys, indices] = slpack(values)
%SLPACK Packs a set of values into unique keys and return the indices for
%each key
%
% [ Syntax ]
%   - [keys, indices] = slpack(values);
%
% [ Arguments ]
%   - values:       the source values to ba packed
%   - keys:         the unique values
%   - indices:      the cell array of indices of the values for the keys
%
% [ Description ]
%   - [keys, indices] = slpack(values) packs the values into a set of 
%     unique keys and return the indices of the values in the input array
%     corresponding to each key.
%
%     Given values, in the output, tne entries in values(indices{i}) will
%     all be equal to keys(i).
%
% [ Remarks ]
%   - This function is an extension of the unique function in matlab. 
%     However, it returns the all the indices corresponding to each key,
%     which are not directly derived from the unique function.
%
% [ History ]
%   - Created by Dahua Lin, on Dec 19, 2007
%

%% main

% pack by unique

if nargout < 2
    keys = unique(values);
else
    [keys, I, J] = unique(values);
end

% group labels

if nargout >= 2

    if issorted(J)
        sJ = J;
        
        [gI0, gI1] = slsegs(sJ);
        indices = arrayfun(@(i0, i1) i0:i1, gI0, gI1, 'UniformOutput', false);
    else    
        [sJ, sidx] = sort(J);
        [gI0, gI1] = slsegs(sJ);
    
        indices = arrayfun(@(i0, i1) sidx(i0:i1), gI0, gI1, 'UniformOutput', false);
    end

    
end


